package io.renren.modules.basedata.service.impl;

import cn.com.taiji.common.manager.net.http.binclient.ApiRequestException;
import cn.com.taiji.sdk.comm.ETCCommHelper;
import cn.com.taiji.sdk.model.comm.protocol.sdts.backlist.OBUBlackListAllDownloadRequest;
import cn.com.taiji.sdk.model.comm.protocol.sdts.backlist.OBUBlackListIncrDownloadRequest;
import io.renren.common.utils.*;
import io.renren.modules.basedata.dao.OBUBlackDownloadDao;
import io.renren.modules.basedata.dao.OperlogDao;
import io.renren.modules.basedata.entity.*;
import io.renren.modules.basedata.service.OBUBlacklistDownloadService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class OBUBlackListDownloadServiceImpl implements OBUBlacklistDownloadService {


    @Autowired
    OBUBlackDownloadDao obuBlackDownloadDao;
    @Autowired
    OperlogDao operlogDao;

    /**
     * @author WANGYP
     * @version 实现OBU黑名单全量下载
     */
    public String obuBlackListDownload() throws Exception {

        tbl_Operlog operlog = new tbl_Operlog();

        Date datetime = new Date();

        Integer infoCount = 0;

        tbl_VersonInfo versionInfo = null;

        String version = DateUtil.formatDateTime1(datetime).substring(0, 8);//YYYYMMDD生成要请求的全量OBU黑名单版本号

        HashMap<String, Object> map = new HashMap<String, Object>();

        map.put("version", version);
        map.put("fileType",2);//用户卡OBU黑名单
        map.put("type", 0);//全量
        map.put("result", 1);//已处理

        /**判断是否存在当天已处理的全量版本记录信息***/
        infoCount = obuBlackDownloadDao.getVersionInfo(map);
        //infoCount =  (Integer) sqlMapClient.queryForObject("download_ORACLE.getVersionInfo", map);

        if(infoCount>0){

            log.info("当天的全量OBU黑名单已下载成功，版本号："+version);

        }else{

            String downloadpath = "D:\\";

            int count=0;//记录全量OBU黑名单数量

            int operResult=0;

            version = DateUtil.formatDateTime1(datetime).substring(0, 8);

            log.info("OBU黑名单全量版本："+version);

            OBUBlackListAllDownloadRequest request =new OBUBlackListAllDownloadRequest();

            request.setVersion(version);

            String fileName = ETCCommHelper.getFileName(request,"65");

            String getFileName ;

            try{

                File file =  ETCCommHelper.download(fileName,request,"D:\\");

                getFileName = file.getName();//获取下载文件名

                log.info("OBU黑名单全量下载成功，下载文件为："+file.getAbsolutePath());

                //先清空黑名单表
                obuBlackDownloadDao.deleteOBUBlackAllListDownInfo();
               // sqlMapClient.delete("download_ORACLE.deleteOBUBlackAllListDownInfo");

                //先在下载路径下解压原始压缩包
                ZIPUtil.unzip(file.getAbsolutePath(),downloadpath , true);
                //获取原始压缩包下的二级压缩包文件
                String filePath = downloadpath+file.getName().substring(0, file.getName().lastIndexOf("."));
                List<File> unzipfiles = ZIPUtil.getFiles(filePath);
                //获取原始压缩包下的二级压缩包(二级压缩包只有一个)
                if(unzipfiles!=null&&unzipfiles.size()>0){
                    File zipfile =  unzipfiles.get(0);//F:\BASIC_CARDBLACKLISTDOWN_RES_65_20171023165050007\20171023.zip

                    String workFilePath = "D:\\unzip\\work";//保存二级压缩包文件至该目录下

                    String successFilePath ="D:\\unzip\\success";//将处理成功的原始压缩包保存至该目录下

                    String errorFilePath ="D:\\unzip\\error";//将处理失败的原始压缩包保存至该目录下

                    String secondParentfileName = zipfile.getName();//二级压缩包文件名带后缀.zip

                    String secondParentpath = secondParentfileName.substring(0, secondParentfileName.lastIndexOf("."));//二级压缩包解压后的文件夹名
                    //将二级压缩包转移至workFilePath下
                    ZIPUtil.moveFile(zipfile.getAbsolutePath(),workFilePath+"\\"+secondParentfileName );//F:\\unzip\\work\\20171023.zip
                    //将二级压缩包在workFilePath解压缩
                    ZIPUtil.unzip(workFilePath+"\\"+secondParentfileName, workFilePath, true);//F:\\unzip\\work\\20171023
                    //获取二级压缩包解压后的各省份压缩包文件(三级压缩包)
                    List<File> secondfiles = ZIPUtil.getFiles(workFilePath+"\\"+secondParentpath);//F:\\unzip\\work\\20171023
                    //逐个对各省份的压缩包进行解压，并对解压后的JSON文件进行解析
                    boolean flag = false;
                    for(int i=0;i<secondfiles.size();i++){
                        //获取某个三级压缩包的文件名
                        String thirdParentfileName = secondfiles.get(i).getName();

                        String thirdParentpath = thirdParentfileName.substring(0, thirdParentfileName.lastIndexOf("."));//

                        System.out.println(secondfiles.get(i).getAbsolutePath());//F:\\unzip\\work\\20171023\\20171023_12.zip
                        //解压三级压缩包
                        ZIPUtil.unzip(workFilePath+"\\"+secondParentpath+"\\"+thirdParentfileName, workFilePath+"\\"+secondParentpath, true);
                        //获取三级压缩包解压后的JSON文件
                        List<File>	thirdfiles = ZIPUtil.getFiles(workFilePath+"\\"+secondParentpath+"\\"+thirdParentpath);//F:\\unzip\\work\\20171023\\20171023\\20171023_12
                        //循环处理每个JSON文件
                        for(int m=0;m<thirdfiles.size();m++){
                            //获取JSON文件中的字符串
                            String jsonStr = ZIPUtil.getjsonStr(thirdfiles.get(m).getAbsolutePath());
                            //字符串转化为JSON数组对象
                            JSONArray jsonArray = JSONArray.fromObject(jsonStr);
                            //循环处理每个JSON对象
                            if(jsonArray!=null&&jsonArray.size()>0){

                                tbl_OBUBlackListDown OBUBlackListDownInfo = new tbl_OBUBlackListDown();

                                try{

                                    //sqlMapClient.startTransaction();

                                    //sqlMapClient.startBatch();

                                    for(int  n = 0; n <jsonArray.size(); n++){

                                        JSONObject jsonObject = jsonArray.getJSONObject(n);
                                        OBUBlackListDownInfo.setInsertTime(DateUtil.formatDateTime6(jsonObject.getString("insertTime")));
                                        OBUBlackListDownInfo.setIssuerId(jsonObject.getString("issuerId"));
                                        OBUBlackListDownInfo.setCreationTime(DateUtil.formatDateTime6(jsonObject.getString("creationTime")));
                                        OBUBlackListDownInfo.setType(jsonObject.getInt("type"));
                                        OBUBlackListDownInfo.setOBUId(jsonObject.getString("OBUId"));
                                        OBUBlackListDownInfo.setStatus(jsonObject.getInt("status"));
                                        OBUBlackListDownInfo.setVersion(version);
                                        //插入数据库
                                        obuBlackDownloadDao.insertOBUBlackAllListDownInfo(OBUBlackListDownInfo);
                                       // sqlMapClient.insert("download_ORACLE.insertOBUBlackAllListDownInfo",OBUBlackListDownInfo);
                                        count++;
                                        flag=true;
                                    }
                                    //sqlMapClient.executeBatch();
                                    //sqlMapClient.commitTransaction();
                                }catch(Exception e){
                                    e.printStackTrace();
                                   // sqlMapClient.getCurrentConnection().commit();
                                }finally{
                                   // sqlMapClient.endTransaction();
                                }

                            }
                        }

                    }

                    //删除workFilePath下的二级压缩包和解压缩文件
                    ZIPUtil.delFile(workFilePath+"\\"+secondParentfileName);//二级压缩包

                    ZIPUtil.deleteDir(new File(workFilePath+"\\"+secondParentpath));//删除解压缩文件及文件下的所有文件

                    ZIPUtil.deleteDir(new File(filePath));//删除解压缩文件及文件下的所有文件

                    if(flag){
                        //将原始压缩包转移至successFilePath下
                        ZIPUtil.moveFile(file.getAbsolutePath(), successFilePath+"\\"+file.getName());

                        operResult =1;

                        versionInfo = getVersionInfo(2,0,version,count,getFileName);

                        obuBlackDownloadDao.insertVersionInfo(versionInfo);
                        //sqlMapClient.insert("download_ORACLE.insertVersionInfo",versionInfo);

                    }else{
                        //将原始压缩包转移至errorFilePath下
                        ZIPUtil.moveFile(file.getAbsolutePath(), errorFilePath+"\\"+file.getName());

                        operResult =0;

                    }

                    operlog = getOperlog(18,2,fileName,file.getName(),operResult, "处理数据条数："+count,"下载OBU全量黑名单文件成功");

                    operlogDao.insertlog(operlog);
                    //sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);

                }

            }catch (IOException e) {
                //TODO 网络异常处理,各省补全
                log.info("下载OBU黑名单全量"+version+"版本IO异常:"+e.getMessage());
                e.printStackTrace();
            }catch (ApiRequestException apie) {
                //TODO 系统自定义异常处理，各省补全
                log.info("下载OBU黑名单全量"+version+"版本Apie异常:"+apie.getMessage());
                apie.printStackTrace();
                System.out.println("错误码："+apie.getErrCode()+" 错误信息："+apie.getMessage());
            }
        }
        return "OBU黑名单全量下载结束...";





    }

    /**封装版本记录信息
     *
     * @param fileType 文件类型1-用户卡黑名单2-OBU黑名单3-车牌黑名单4-车牌灰名单
     * @param type 0-全量1-增量
     * @param version 版本号
     * @param count 数据条数
     * @param getFileNme 下载文件名
     * **/
    public tbl_VersonInfo getVersionInfo(int fileType,int type,String version,int count,String getFileNme){

        tbl_VersonInfo versionInfo = new tbl_VersonInfo();
        String recordId = DateUtil.formatDateTime1(new Date())+fileType+type;
        versionInfo.setRecordId(recordId);
        versionInfo.setFileType(fileType);
        versionInfo.setType(type);
        versionInfo.setVersion(version);
        versionInfo.setDownCount(count);
        versionInfo.setCreatTime(new Date());
        versionInfo.setResult(1);
        versionInfo.setDealTime(new Date());
        versionInfo.setPackageName(getFileNme);

        return versionInfo;
    }


    //获取operlog信息
    public tbl_Operlog getOperlog(int operType,int softType,String sendFileName,String reFileName,int operResult,String reResult, String content){
        tbl_Operlog operlog = new tbl_Operlog();
        operlog.setWastesn(new GUID().toString());
        operlog.setOperTime(new Date());
        operlog.setOperType(operType);
        operlog.setSoftType(softType);
        operlog.setSendFileName(sendFileName);
        operlog.setReFileName(reFileName);
        operlog.setOperResult(operResult);
        operlog.setReResult(reResult);
        operlog.setContent(content);
        return operlog;
    }

    private String secondParentfileName;//二级压缩包文件名
    private String secondParentpath; //二级压缩包解压后的文件夹名

    /**
     * @author WANGYP
     * @version 实现OBU黑名单增量下载
     */
    @SuppressWarnings({ "unused", "unchecked" })
    public String obuBlackListIncreDownload() throws Exception {

        tbl_Operlog operlog = new tbl_Operlog();

        Date datetime = new Date();

        List<tbl_VersonInfo> versionInfoList = null;

        String full_version = DateUtil.formatDateTime1(datetime).substring(0, 8);//全量用户卡OBU黑名单版本

        String inc_version = DateUtil.formatDateTime1(datetime).substring(0, 8)+"0000";//默认增量黑名单版本为当天0时0分

        int full_infoCount = 0;//全量记录数据总数

        int inc_infoCount = 0;//增量记录数据总数

        int operResult=0;

        tbl_VersonInfo versionInfo = null;

        String downloadPath = "D:\\";

        HashMap<String, Object> full_versionMap = new HashMap<String, Object>();

        full_versionMap.put("version", full_version);
        full_versionMap.put("fileType",2);//OBU黑名单
        full_versionMap.put("type", 0);//全量
        full_versionMap.put("result", 1);//已处理

        /**判断是否存在当天已处理的全量版本记录信息***/
        full_infoCount = obuBlackDownloadDao.getVersionInfo(full_versionMap);
        //full_infoCount =  (Integer) sqlMapClient.queryForObject("download_ORACLE.getVersionInfo", full_versionMap);

        /***如果不存在已经处理成功的当天的全量黑名单下发记录，则不向部中心请求增量黑名单数据***/
        if(full_infoCount==0){

            log.info("今天的全量用户卡黑名单还未下载，暂不向部中心发送增量用户卡黑名单请求");

        }else{

            /**1.如果存在已经处理成功的当天的全量黑名单下发记录，则判断是否有当天的已处理的增量黑名单记录；
             * 2.如果没有，则向部中心请求当天零时零分的增量黑名单；
             * 3.如果存在当天的已处理的增量黑名单记录，则根据最新已处理的黑名单版本请求15分钟后的增量黑名单版本*/
            HashMap<String, Object> inc_versionMap = new HashMap<String, Object>();

            inc_versionMap.put("version", full_version);
            inc_versionMap.put("fileType",2);//OBU黑名单
            inc_versionMap.put("type", 1);//增量
            inc_versionMap.put("result", 1);//已处理
            versionInfoList = obuBlackDownloadDao.getVersionInfoList(inc_versionMap);
            //versionInfoList =  sqlMapClient.queryForList("download_ORACLE.getVersionInfoList", inc_versionMap);//获取增量版本信息

            OBUBlackListIncrDownloadRequest request = new OBUBlackListIncrDownloadRequest();

            if(versionInfoList!=null&&versionInfoList.size()>0){

                inc_version = getInc_version(versionInfoList.get(0).getVersion());

                if(inc_version==null){

                    log.info("增量版本不存在,程序退出等待下次执行...");

                    return "增量版本不存在,程序退出等待下次执行...";

                }

            }

            log.info("OBU黑名单增量版本号："+inc_version);

            request.setVersion(inc_version);

            String fileName = ETCCommHelper.getFileName(request,"65");

            String getFileName;

            try{

                File file =  ETCCommHelper.download(fileName,request,"D:\\");

                getFileName = file.getName();

                log.info("OBU黑名单增量下载成功，下载文件为："+file.getAbsolutePath());

                //先在下载路径下解压原始压缩包
                ZIPUtil.unzip(file.getAbsolutePath(),downloadPath , true);
                //获取原始压缩包下的二级压缩包文件
                String filePath = downloadPath+file.getName().substring(0, file.getName().lastIndexOf("."));

                List<File> unzipfiles = ZIPUtil.getFiles(filePath);//201709150030.zip

                String workFilePath = "D:\\unzip\\workObu";//保存二级压缩包文件至该目录下

                String successFilePath ="D:\\unzip\\success";//将处理成功的原始压缩包保存至该目录下

                String errorFilePath ="D:\\unzip\\error";//将处理失败的原始压缩包保存至该目录下
                //获取原始压缩包下的二级压缩包(二级压缩包是多个版本的增量名单)201709150030.zip
                if(unzipfiles!=null&&unzipfiles.size()>0){

                    for(int i=0;i<unzipfiles.size();i++){

                        File zipfile =  unzipfiles.get(i);//F:\BASIC_CARDBLACKLISTDOWN_RES_65_20171023165050007\201709150030.zip

                        secondParentfileName = zipfile.getName();//二级压缩包文件名带后缀.zip

                        secondParentpath = secondParentfileName.substring(0, secondParentfileName.lastIndexOf("."));//二级压缩包解压后的文件夹名
                        //将二级压缩包转移至workFilePath下
                        ZIPUtil.moveFile(zipfile.getAbsolutePath(),workFilePath+"\\"+secondParentfileName );//F:\\unzip\\work\\201709150030.zip
                        //将二级压缩包在workFilePath解压缩
                        ZIPUtil.unzip(workFilePath+"\\"+secondParentfileName, workFilePath, true);//F:\\unzip\\work\\201709150030
                        //获取二级压缩包解压后的各省份压缩包文件(三级压缩包)
                        List<File> secondfiles = ZIPUtil.getFiles(workFilePath+"\\"+secondParentpath);//F:\\unzip\\work\\201709150030

                        for(int m=0;m<secondfiles.size();m++){
                            String secondfileName = secondfiles.get(m).getName();//F:\\unzip\\work\\201709150030\\201709150030_data.zip
                            String currtentPath = workFilePath+"\\"+secondParentpath;
                            Validate validate = new Validate();
                            ArrayList<String> validatelist = new ArrayList<String>();
                            ArrayList<String> obuBlacklist = new ArrayList<String>();
                            List<tbl_OBUBlackListDown> allobuBlackList = new ArrayList<tbl_OBUBlackListDown>();
                            if(secondfileName.indexOf(".json")!=-1){
                                //解析校验文件至内存
//							validate =ZIPUtil.analysisValidateJson(secondfiles.get(m));
//							//删除校验文件
//							secondfiles.get(m).delete();
//							validatelist = new ArrayList<String>();
//							for(Abstract abstrac:validate.getAbstract()){
//								validatelist.add(abstrac.getId());
//							}
                            }else{
                                //解压数据包
                                ZIPUtil.unzip(currtentPath+"\\"+secondfiles.get(m).getName(),  currtentPath, true);//F:\\unzip\\work\\201709150030\\201709150030_data
                                //删除数据包
                                ZIPUtil.delFile(currtentPath+"\\"+secondfiles.get(m).getName());
                                //获取该版本的各省份压缩包
                                List<File> zfileListfxf =ZIPUtil.getFiles(currtentPath+"\\"+secondfileName.substring(0, secondfileName.lastIndexOf(".")));//获取F:\\unzip\\work\\201709150030\\201709150030下的压缩包

                                for (int k = 0; k < zfileListfxf.size(); k++) {

                                    List<tbl_OBUBlackListDown> obuBlackList=ZIPUtil.analysisJson(zfileListfxf.get(k),tbl_OBUBlackListDown.class);
                                    //逐条写入数据库
                                    for(int n=0;n<obuBlackList.size();n++){
                                        obuBlackList.get(n).setVersion(inc_version);
                                        try{
                                            if(obuBlackList.get(n).getStatus()==1){//如果是加入黑名单，则执行插入语句
                                                obuBlackDownloadDao.insertOBUBlackIncreListDownInfo(obuBlackList.get(n));
                                               // sqlMapClient.insert("download_ORACLE.insertOBUBlackIncreListDownInfo",obuBlackList.get(n));
                                            }else{//如果是解除黑名单，则执行删除语句
                                                obuBlackDownloadDao.deleteOBUBlackIncreListDownInfo(obuBlackList.get(0));
                                                //sqlMapClient.delete("download_ORACLE.deleteOBUBlackIncreListDownInfo",obuBlackList.get(n));
                                            }

                                            inc_infoCount++;

                                        }catch(Exception e){

                                            inc_infoCount++;

                                            continue;
                                        }

                                    }

                                    System.out.println(obuBlackList.size());

                                }
                                //每处理完一个版本的文件需要进行校验

//							allobuBlackList = sqlMapClient.queryForList("download_ORACLE.allobuBlackListDownInfo");
//
//							obuBlacklist = getOBUBlacklist(allobuBlackList);
//
//							if(obuBlacklist==validatelist){
//
//								System.out.println("校验成功!");
//
//							}else{
//
//								System.out.println("校验失败!");
//
//							}


                            }


                        }


                    }
                    //将原始压缩包转移至successFilePath目录下
                    ZIPUtil.moveFile(file.getAbsolutePath(),successFilePath+"\\"+file.getName());
                    //将workFilePath下的文件全部删掉
                    ZIPUtil.deleteDir(new File(workFilePath+"\\"+secondParentfileName));
                    ZIPUtil.deleteDir(new File(workFilePath+"\\"+secondParentpath));
                    //将下载目录下的解压缩文件全部删掉
                    ZIPUtil.delFile(filePath);
                    /**处理成功，向版本记录表中写入信息**/

                    versionInfo = getVersionInfo(2,1,inc_version,inc_infoCount,getFileName);
                    obuBlackDownloadDao.insertVersionInfo(versionInfo);
                    //sqlMapClient.insert("download_ORACLE.insertVersionInfo",versionInfo);


                }else{//下载失败
                    System.out.println("下载失败");
                    log.info("下载失败");
                }

            }catch (IOException e) {
                //TODO 网络异常处理,各省补全
                log.info("下载OBU黑名单增量"+inc_version+"版本IO异常:"+e.getMessage());
                e.printStackTrace();
            }catch (ApiRequestException apie) {
                //TODO 系统自定义异常处理，各省补全

                if(apie.getErrCode()==711){//针对711异常，部中心无对应增量版本数据进行处理

                    versionInfo = getVersionInfo(2,1,inc_version,inc_infoCount,"无数据");
                    obuBlackDownloadDao.insertVersionInfo(versionInfo);
                    //sqlMapClient.insert("download_ORACLE.insertVersionInfo",versionInfo);
                }

                log.info("下载OBU黑名单增量"+inc_version+"版本Apie异常:"+apie.getMessage());
                apie.printStackTrace();
                System.out.println("错误码："+apie.getErrCode()+" 错误信息："+apie.getMessage());
            }
        }
        return "OBU黑名单增量下载结束...";

    }


    /**
     * 获取将要请求的黑名单版本号
     *
     * **/
    public String getInc_version(String inc_version){

        String min = inc_version.substring(10,12);

        String hour = inc_version.substring(8,10);

        String date = inc_version.substring(0,8);

        if(min.equals("00")){

            min = "15";

        }else if(min.equals("15")){

            min = "30";

        }else if(min.equals("30")){

            min = "45";

        }else{

            min ="00";

            hour = OperType.compStr(String.valueOf(Integer.valueOf(hour)+1),2);

            if(hour.equals("24")){//如果已经是当天最后一个版本，则返回null,不再进行处理

                return null;
            }
        }

        inc_version = date+hour+min;

        return inc_version;
    }









    /**
     *从OBU全量黑名单中每10000条获取一条数据;
     *
     * */
    public ArrayList<String> getOBUBlacklist(List<tbl_OBUBlackListDown> allobuBlackList){
        ArrayList<String> obuBlacklist = new ArrayList<String>();

        int m = allobuBlackList.size()/10000;//取整

        int n = allobuBlackList.size()%10000;//取余

        int num = 0;

        if(n==0){

            for(int k=0;k<m;k++){

                num = k*10000+1;

                obuBlacklist.add(allobuBlackList.get(num).getOBUId());

            }


        }else{

            for(int j=0;j<m+1;j++){

                num = j*10000+1;

                obuBlacklist.add(allobuBlackList.get(num).getOBUId());

            }

        }

        return obuBlacklist;
    }

    /**
     * @author WANGYP
     * @version 实现OBU黑名单从部中心下发表下发至省中心下发表
     */
    @SuppressWarnings("unchecked")
    public String OBUBlackDownloadCenter() throws Exception {
        log.info("开始查询营改增全量obu黑名单数据");

        List<Tbl_OBUBlacklist> OBUBlackList = new ArrayList<Tbl_OBUBlacklist>();

        int cardType=1;//0-用户卡1-OBU
        int cardNum = obuBlackDownloadDao.allOBUBlackListCount();
        //int cardNum = (Integer) sqlMapClient.queryForObject("user_ORACLE.allOBUBlackListCount");

        TBL_CardStListPara cardSt = null;//中心下发黑名单表

        boolean flag =true;

        /**根据下发记录获取黑名单数据**/

        if(cardNum>0){//如果数据不为空，则清空中心库数据

            try{

               // sqlMapClient2.startTransaction();

               // sqlMapClient2.startBatch();

                obuBlackDownloadDao.deleteBlackList(cardType);
                //sqlMapClient2.delete("user_ORACLE.deleteBlackList",cardType);//先清空OBU数据

               // sqlMapClient2.executeBatch();

                //sqlMapClient2.commitTransaction();

            }catch(Exception e){
                log.info("清空OBU数据失败："+e.getMessage());
                //sqlMapClient2.getCurrentConnection().rollback();
                flag = false;
            }finally{
                //sqlMapClient2.endTransaction();
            }

            int onerun = 50000;

            int runnum =0;

            runnum = cardNum%onerun==0?(cardNum/onerun):(cardNum/onerun)+1;

            try{
                //sqlMapClient2.startTransaction();

                for(int r =1;r<=runnum;r++){
                    log.info(" 开始查询第"+(r)+"批OBU数据");
                    HashMap<String,Object> paraMap = new HashMap<String,Object>();
                    paraMap.put("limit", onerun);
                    paraMap.put("start", (r - 1) * onerun);
                    OBUBlackList = obuBlackDownloadDao.getOBUBlackList(paraMap);
                   // OBUBlackList =sqlMapClient.queryForList("user_ORACLE.getOBUBlackList", paraMap);//根据版本号和表名获取黑名单数据

                   // sqlMapClient2.startBatch();
                    for(int i=OBUBlackList.size()-1;i>-1;i--){

                        cardSt = genCardStPara(OBUBlackList.get(i));//黑名单数据转化
                        obuBlackDownloadDao.insertBlackList(cardSt);
                        //sqlMapClient2.insert("user_ORACLE.insertBlackList", cardSt);

                    }
                    //sqlMapClient2.executeBatch();

                    OBUBlackList.clear();

                    log.info("第"+(r)+"批OBU数据处理完成");

                }
                //sqlMapClient2.commitTransaction();

            }catch(Exception e){
                log.info("OBU批处理失败："+e.getMessage());
               // sqlMapClient2.getCurrentConnection().rollback();
                flag = false;
            }finally{
               // sqlMapClient2.endTransaction();
            }


            //更新下发记录
            if(flag){

               // sqlMapClient2.update("check_ORACLE.updateConfig");

                log.info("OBU更新下发记录时间:"+DateUtil.formatDateTime(new Date()));

            }



        }else{

            log.info("当前无新下发的黑名单记录");

        }
        return "用户卡黑名单全量下载至省中心结束...";
    }

    private TBL_CardStListPara genCardStPara(Tbl_OBUBlacklist OBUBlack){

        TBL_CardStListPara cardStListPara = new TBL_CardStListPara();

        try{

            String obuId = OBUBlack.getOBUId();//卡号

            cardStListPara.setCardId(obuId);

            if(obuId!=null && !obuId.equals("null")){

                cardStListPara.setCardType(1);//0-卡1-OBU

                /***
                 * 交通部定义OBU黑名单类型
                 * 1-标签挂失
                 * 2-无签挂起
                 * 3-无签注销
                 * 4-车型不符
                 * **/
                /***
                 * 青海省定义OBU黑名单类型
                 * 1-挂失卡
                 * 2-禁用
                 * 3-注销
                 * 4-黑名单电子标签
                 * **/

                if(OBUBlack.getType()==1){//挂失

                    cardStListPara.setStatus(1);//挂失

                }else if(OBUBlack.getType()==3){//无签注销

                    cardStListPara.setStatus(3);//注销

                }else if(OBUBlack.getType()==4){//车型不符

                    cardStListPara.setStatus(4);//

                }else{//无签挂起

                    cardStListPara.setStatus(2);//禁用

                }


            }else{
                log.info("无对应OBU号");
            }

            cardStListPara.setNetNo(Integer.valueOf(OBUBlack.getIssuerId().substring(0, 2)+OBUBlack.getIssuerId().substring(4, 6)));//网络编号

            cardStListPara.setIssuerId(OBUBlack.getIssuerId());//发行方id

            cardStListPara.setListType(0); //名单类型0:全量1:增量

            cardStListPara.setVersion(OBUBlack.getVersion());  //版本号

            cardStListPara.setStartTime(OBUBlack.getCreationTime());//生效时间

            cardStListPara.setUpdateTime(new Date());          //更新时间

            cardStListPara.setLicense("0");    //营改增后无车牌号

            cardStListPara.setSpare2(DateUtil.formatDateTime(new Date()));

        }catch(Exception e){

            log.error("OBU黑名单由中间表格式转为本系统格式时异常"+e.getMessage());

            e.printStackTrace();

        }

        return cardStListPara;

    }



}
